package com.company;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.DoubleSummaryStatistics;
import java.util.Scanner;
import java.util.concurrent.SynchronousQueue;

/**
 * Created by Administrator on 2016.8.26.
 */
public class Import {
    private ArrayList<ArrayList<Double>> arrayLists;

    public Import(String address,int sheetNumber,int x1,int y1,int x2,int y2) throws IOException, BiffException {
        arrayLists=new ArrayList<>();
        Workbook workbook=Workbook.getWorkbook(new File(address));
        Sheet sheet=workbook.getSheet(sheetNumber);

        for (int j=y1-1;j<y2;j++){
            ArrayList<Double> numbers=new ArrayList<>();
            for (int i=x1-1;i<x2;i++){
                try {
                    numbers.add(Double.valueOf(sheet.getCell(j,i).getContents()));
                }catch (Exception e){
                    numbers.add(0.0);
                }
            }
            arrayLists.add(numbers);
        }

        ArrayList<Integer> sign=new ArrayList<>();
        ArrayList<Integer> names=new ArrayList<>();

        for (int i=y1-1;i<y2;i++){
            names.add(Integer.valueOf(sheet.getCell(i,x1-2).getContents().substring(4)));
            sign.add(i-y1+1);
        }

        for (int i=0;i<names.size();i++){
            for (int j=0;j<names.size()-1;j++){
                if(names.get(j)>names.get(j+1)){
                    int t=0;
                    t=names.get(j);
                    names.set(j,names.get(j+1));
                    names.set(j+1,t);

                    t=sign.get(j);
                    sign.set(j,sign.get(j+1));
                    sign.set(j+1,t);
                }
            }
        }

        ArrayList<ArrayList<Double>>newArrayLists=new ArrayList<>();

        for (int i=0;i<arrayLists.size();i++){
            newArrayLists.add(arrayLists.get(sign.get(i)));
        }

        arrayLists=newArrayLists;

        PrintWriter output=new PrintWriter(new File("a"+(sheetNumber+1)+".txt"));

        for (ArrayList<Double> numbers:arrayLists){
            for (double d:numbers){
                output.print(d+" ");
            }

            output.println();
        }

        output.close();
    }
}
